﻿package com.hadron
{
	import flash.display.BitmapData;
	
	public final class ImageCache 
	{
		private static var _instance:ImageCache = new ImageCache();
		public static function get Instance():ImageCache
		{
			return _instance;
		}
		
		public function ImageCache():void
		{
			if (_instance != null)
			{
				throw new Error("TO JEST SINGLETON QRWA! NIE DZIS!");
			}
		}
		
		private const CACHE_LIMIT:int = 100;
		private var cache:Array = [];
		
		public function addItem(bmpData:BitmapData, url:String):void
		{
			cache.push( { bmpData: bmpData, url: url } );
			if (cache.length > CACHE_LIMIT)
			{
				cache.shift();
			}
		}
		
		public function getURLAt(index:int):String
		{
			return cache[index].url;
		}
		
		public function getBitmapDataAt(index:int):BitmapData
		{
			return cache[index].bmpData as BitmapData;
		}
		
		public function indexOf(obj:Object):int
		{
			var i:int;
			if (obj is BitmapData)
			{
				for (i = 0; i < cache.length; ++i)
				{
					if (cache[i].bmpData == obj)
					{
						return i;
					}
				}
			}
			else if (obj is String)
			{
				for (i = 0; i < cache.length; ++i)
				{
					if (cache[i].url == obj)
					{
						return i;
					}
				}
			}
			return -1;
		}
		
		public function contains(obj:Object):Boolean
		{
			return indexOf(obj)>-1;
		}
	}	
}